package com.itheima.reggie.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R insertNewCategory(@RequestBody Category category, HttpServletRequest request) {

        //生成create_time
        //生成update_time
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        //生成create_user
        //生成update_user
        Long isLogin = (Long) request.getSession().getAttribute("isLogin");
        category.setCreateUser(isLogin);
        category.setUpdateUser(isLogin);

        categoryService.insertNewCategory(category);
        return R.success("新增分类成功");
    }


    /**
     * 查询指定页,按照category表中sort字段排序
     *
     * @return
     */
    @GetMapping("/page")
    public R selectByPage(int page, int pageSize) {
        PageInfo<Category> pageInfo = categoryService.selectByPage(page, pageSize);
        return R.success(pageInfo);//已将前端取数据时改为res.data.list
    }


    @DeleteMapping
    public R deleteById(String id) {

        String resultString = categoryService.deleteById(id);
        if (!resultString.equals("success")) {
            return R.error(resultString);
        } else {
            return R.success("分类信息删除成功");
        }

    }


    @PutMapping
    public R updateById(@RequestBody Category category, HttpServletRequest request) {
        //生成update_time
        category.setUpdateTime(LocalDateTime.now());
        //生成update_user
        Long isLogin = (Long) request.getSession().getAttribute("isLogin");
        category.setUpdateUser(isLogin);
        categoryService.updateById(category);
        return R.success("分类修改成功");
    }


    @GetMapping("/list")
    public R selectByType(Integer type) {
        List<Category> categories = null;
        if (type != null) {
            categories = categoryService.selectByType(type);
        } else {
            categories = categoryService.selectAll();
        }
        return R.success(categories);
    }
}
